const fs = require('fs')

const webpack = require('webpack')

const {createdBundleServer} = require('./bundle/server')
const {createdHMRServer} = require('./hmr/server')

class GengDevServer {
  config = null
  compiler = null
  bundleServer = null
  hmrServer = null

  constructor(config) {
    this.config = config
    this.compiler = webpack(config)
  }

  watch(port, wsPort) {
    // 启动 Bundle Server
    this.bundleServer = createdBundleServer(this.config, port, wsPort)
    this.bundleServer.listen()

    // 启动 HMR Server
    this.hmrServer = createdHMRServer(wsPort)
    this.hmrServer.listen()

    // 绑定 webpack 重新打包事件
    let lastHash = ''
    this.compiler.hooks.done.tap('webpack-dev-server', (stats) => {
      // lastHash = stats.hash
      console.log('rebuild')
      this.hmrServer.sendAll('reload')
    })

    // 启动 webpack watch
    this.compiler.watch({}, err => {
    })

    console.log('WDS: http://localhost:' + port)
  }
}

function bootstrap(configFile, port = 4000, wsPort=4004) {
  if (!fs.existsSync(configFile)) {
    throw Error('config file does not exists')
  }

  const config = require(configFile)
  const devServerPort = config?.devServer?.port || port

  const devServer = new GengDevServer(require(configFile))
  devServer.watch(devServerPort, wsPort)
}

module.exports = {
  bootstrap,
  DevServer: GengDevServer
}
